﻿using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using SuperJoe.Framework.Caching;
using SuperJoe.Framwork.Web;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.IO;
using System.Drawing.Imaging;
using WWX.Admin.Web.Models;
using WWX.Admin.BLL;

namespace WWX.Admin.Web.Controllers
{
    public class AccountController : Controller
    {
        [HttpGet]
        public ActionResult Login()
        {
            return View(new LoginVM() { ValidationCodeId = Guid.NewGuid().ToString() });
        }

        [HttpPost]
        public ActionResult Login(LoginVM vm)
        {
            if (ModelState.IsValid)
            {
                var validationCode = CacheManager.Cache.Get<string>("admin_validation_code_" + vm.ValidationCodeId);
                if (validationCode != vm.ValidationCode)
                {
                    vm.ValidationCode = null;
                    ModelState.AddModelError("FriendlyMessage", "验证码失效或者错误");
                    return View(vm);
                }

                UserBLL userBll = new UserBLL();
                var member = userBll.Get(vm.Account, vm.Password);
                if (member != null && member.IsActive)
                {
                    IdentityManager.SignIn(new IdentityUser() { Name = member.Account, Account = member.Account, Id = member.Id }, vm.IsRememberMe ? (DateTime?)DateTime.Now.AddDays(30) : null);
                    return Redirect("/");
                }

                else if (member == null)
                {

                    ModelState.AddModelError("FriendlyMessage", "账号或者密码有错误");
                    return View(vm);
                }
                else
                {
                    ModelState.AddModelError("FriendlyMessage", "此账号已被禁用");
                    return View(vm);
                }
            }
            else
            {
                return View(vm);
            }
        }

        public ActionResult Logout()
        {
            IdentityManager.SignOut();
            return Redirect(ConfigData.LoginUrl);
        }

        public ActionResult GetValidationCode(string ValidationCodeId)
        {
            var vCode = new ValidationCode();
            var code = vCode.CreateValidateCode(4);

            CacheManager.Cache.Add<string>("admin_validation_code_" + ValidationCodeId, code, new TimeSpan(0, 5, 0));//验证码缓存5分钟。

            var bytes = CreateValidateGraphic(code);
            return File(bytes, @"image/jpeg");
        }

        /// <summary>
        /// 创建验证码的图片
        /// </summary>
        /// <param name="validateCode">验证码</param>
        /// <returns>字节数组</returns>
        public byte[] CreateValidateGraphic(string validateCode)
        {
            //var image = new Bitmap((int)Math.Ceiling(validateCode.Length * 12.0), 22);
            var image = new Bitmap(110, 45);
            var g = Graphics.FromImage(image);
            try
            {
                //生成随机生成器
                var random = new Random();
                //清空图片背景色
                g.Clear(Color.White);
                //画图片的干扰线
                for (var i = 0; i < 25; i++)
                {
                    var x1 = random.Next(image.Width);
                    var x2 = random.Next(image.Width);
                    var y1 = random.Next(image.Height);
                    var y2 = random.Next(image.Height);
                    //g.DrawLine(new Pen(Color.Silver), x1, y1, x2, y2);
                }
                var font = new Font("Arial", 28, (FontStyle.Bold | FontStyle.Italic));
                var brush = new LinearGradientBrush(new Rectangle(0, 0, image.Width, image.Height), Color.Blue, Color.DarkRed, 1.2f, true);
                g.DrawString(validateCode, font, brush, 3, 2);
                //画图片的前景干扰点
                for (var i = 0; i < 100; i++)
                {
                    var x = random.Next(image.Width);
                    var y = random.Next(image.Height);
                    image.SetPixel(x, y, Color.FromArgb(random.Next()));
                }
                //画图片的边框线
                g.DrawRectangle(new Pen(Color.Silver), 0, 0, image.Width - 1, image.Height - 1);
                //保存图片数据
                var stream = new MemoryStream();
                image.Save(stream, ImageFormat.Jpeg);
                //输出图片流
                return stream.ToArray();
            }
            finally
            {
                g.Dispose();
                image.Dispose();
            }
        }
    }
}